/**
 * Copyright 2013 Mr.Hai Mobile Developer. All rights reserved.
 * HAI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hector.meinewerk.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.commonsware.cwac.cache.SimpleWebImageCache;
import com.commonsware.cwac.thumbnail.ThumbnailBus;
import com.commonsware.cwac.thumbnail.ThumbnailMessage;
import com.hector.meinewerk.client.R;
import com.hector.meinewerk.common.BaseActivity;
import com.hector.meinewerk.common.GlobalInfo;
import com.hector.meinewerk.constants.Constants;
import com.hector.meinewerk.listener.OnDialogControlListener;

/**
 * 
 * global utils
 * 
 * @author: HaiTC3
 * @version: 1.1
 * @since: 1.0 | Mar 7, 2013
 */
public class GlobalUtils {
	private static Method overridePendingTransition;

	/**
	 * chup hinh
	 * 
	 * @author: HaiTC
	 * @param activity
	 * @param requestCode
	 * @return
	 * @return: File
	 * @throws:
	 */
	public static File takePhoto(BaseActivity activity, int requestCode) {
		final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		final File path = new File(Environment.getExternalStorageDirectory(),
				GlobalInfo.getInstance().getAppContext().getPackageName());
		if (!path.exists()) {
			path.mkdir();
		}
		String fileName = Constants.TEMP_IMG;
		File retFile = new File(path, fileName);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(retFile));
		// activity.isSaveInstance = true;
		activity.startActivityForResult(intent, requestCode);
		return retFile;
	}

	/**
	 * set max lenght cho edit text
	 * 
	 * @author: HaiTC
	 * @param edText
	 * @param maxLength
	 * @return: void
	 * @throws:
	 */
	public static void setEditTextMaxLength(EditText edText, int maxLength) {
		InputFilter[] inputFilters = new InputFilter[1];
		inputFilters[0] = new InputFilter.LengthFilter(maxLength);
		edText.setFilters(inputFilters);
	}

	/**
	 * 
	 * convert from dip to pixcel
	 * 
	 * @param @param dips
	 * @param @return
	 * @return: int
	 * @author: HaiTC3
	 * @date: Mar 7, 2013
	 */
	public static int dip2Pixel(int dips) {
		int ret = (int) (GlobalInfo.getInstance().getAppContext()
				.getResources().getDisplayMetrics().density
				* dips + 0.5f);
		return ret;
	}

	/**
	 * save object vao file
	 * 
	 * @author: HaiTC
	 * @param object
	 * @param fileName
	 * @return: void
	 * @throws:
	 */
	public static void saveObject(Object object, String fileName) {
		try {
			FileOutputStream fos = GlobalInfo.getInstance().getAppContext()
					.openFileOutput(fileName, Context.MODE_PRIVATE);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
			oos.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Doc file
	 * 
	 * @author: HaiTC
	 * @param ct
	 * @param fileName
	 * @return: void
	 * @throws:
	 */
	public static Object readObject(String fileName) {
		Object object = null;
		try {
			if (isExistFile(fileName)) {
				FileInputStream fis = GlobalInfo.getInstance().getAppContext()
						.openFileInput(fileName);
				if (fis != null) {// ton tai file
					ObjectInputStream ois = new ObjectInputStream(fis);
					object = ois.readObject();
					ois.close();
					fis.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

	/**
	 * 
	 * check file exist
	 * 
	 * @param @param fileName
	 * @param @return
	 * @return: boolean
	 * @author: HaiTC3
	 * @date: Mar 7, 2013
	 */
	public static boolean isExistFile(String fileName) {
		try {
			if (!StringUtil.isNullOrEmpty(fileName)) {
				String[] s = GlobalInfo.getInstance().getAppContext()
						.fileList();
				for (int i = 0, size = s.length; i < size; i++) {
					if (fileName.equals(s[i].toString())) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * Xoa all file
	 * 
	 * @author: HaiTC
	 * @param ct
	 * @param fileName
	 * @return
	 * @return: boolean
	 * @throws:
	 */
	public static void deleteListFiles() {
		Object object = null;
		try {// "data/data/" + ct.getPackageName() + "/" +
			String[] s = GlobalInfo.getInstance().getAppContext().fileList();
			for (int i = 0, size = s.length; i < size; i++) {
				GlobalInfo.getInstance().getAppContext()
						.deleteFile(s[i].toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Tao resouce id de dang nhap xmpp
	 * 
	 * @author: HaiTC
	 * @return
	 * @return: String
	 * @throws:
	 */
	public static String generateXMPPResouceId() {
		return "android_" + Calendar.getInstance().getTimeInMillis();
	}

	public static void setColorSeperatorListView(ListView lv) {
		int[] colors = { 0, 0xffafadb0, 0 }; // red for the example 0xafadb0
		lv.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
		lv.setDividerHeight(1);
	}

	static {
		try {
			overridePendingTransition = Activity.class
					.getMethod(
							"overridePendingTransition", new Class[] { Integer.TYPE, Integer.TYPE }); //$NON-NLS-1$
		} catch (NoSuchMethodException e) {
			overridePendingTransition = null;
		}
	}

	/**
	 * Calls Activity.overridePendingTransition if the method is available
	 * (>=Android 2.0)
	 * 
	 * @param activity
	 *            the activity that launches another activity
	 * @param animEnter
	 *            the entering animation
	 * @param animExit
	 *            the exiting animation
	 */
	public static void overridePendingTransition(Activity activity,
			int animEnter, int animExit) {
		if (overridePendingTransition != null) {
			try {
				overridePendingTransition.invoke(activity, animEnter, animExit);
			} catch (Exception e) {
				// do nothing
			}
		}
	}

	/**
	 * show dialog confirm 2 button
	 * 
	 * @author: HaiTC
	 * @param view
	 * @param notice
	 * @param ok
	 * @param actionOk
	 * @param cancel
	 * @param actionCancel
	 * @param data
	 * @return: void
	 * @throws:
	 */

	public static void showDialogConfirm(final BaseActivity view,
			String notice, String ok, final int actionOk, String cancel,
			final int actionCancel, final Object data) {
		if (view != null) {
			AlertDialog alertDialog = new AlertDialog.Builder(view).create();
			alertDialog.setMessage(notice);
			if (ok != null && !Constants.STR_BLANK.equals(ok)) {
				alertDialog.setButton(ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								view.onEvent(actionOk, null, data);
								dialog.dismiss();
							}
						});
			}
			if (cancel != null && !Constants.STR_BLANK.equals(cancel)) {
				alertDialog.setButton2(cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								view.onEvent(actionCancel, null, data);
								dialog.dismiss();
							}
						});
			}
			alertDialog.show();
		}
	}

	/**
	 * Remove view reference
	 * 
	 * @author: HaiTC
	 * @param view
	 * @return: void
	 * @throws:
	 */
	private static void unbindViewReferences(View view) {
		// set all listeners to null (not every view and not every API level
		// supports the methods)
		try {
			view.setOnClickListener(null);
		} catch (Throwable mayHappen) {
		}
		;
		try {
			view.setOnCreateContextMenuListener(null);
		} catch (Throwable mayHappen) {
		}
		;
		try {
			view.setOnFocusChangeListener(null);
		} catch (Throwable mayHappen) {
		}
		;
		try {
			view.setOnKeyListener(null);
		} catch (Throwable mayHappen) {
		}
		;
		try {
			view.setOnLongClickListener(null);
		} catch (Throwable mayHappen) {
		}
		;
		try {
			view.setOnClickListener(null);
		} catch (Throwable mayHappen) {
		}
		;

		// set background to null
		Drawable d = view.getBackground();
		if (d != null)
			d.setCallback(null);
		if (view instanceof ImageView) {
			ImageView imageView = (ImageView) view;
			d = imageView.getDrawable();
			if (d != null)
				d.setCallback(null);
			imageView.setImageDrawable(null);
			imageView.setBackgroundDrawable(null);
			imageView = null;
		}

		// destroy webview
		if (view instanceof WebView) {
			((WebView) view).destroyDrawingCache();
			((WebView) view).destroy();
		}
		view = null;
	}

	/**
	 * Removes the reference to the activity from every view in a view hierarchy
	 * (listeners, images etc.). This method should be called in the onDestroy()
	 * method of each activity
	 * 
	 * @author: HaiTC
	 * @param viewID
	 *            normally the id of the root layout
	 * @return
	 * @throws:
	 */

	public static void nullViewDrawablesRecursive(View view) {
		if (view != null) {
			try {
				ViewGroup viewGroup = (ViewGroup) view;

				int childCount = viewGroup.getChildCount();
				for (int index = 0; index < childCount; index++) {
					View child = viewGroup.getChildAt(index);
					nullViewDrawablesRecursive(child);
				}
			} catch (Exception e) {
			}

			unbindViewReferences(view);
		}
	}

	/**
	 * tao text view nhieu mau sac
	 * 
	 * @author: HaiTC
	 * @param activity
	 * @param listener
	 * @param menu
	 * @param title
	 * @param tip
	 * @return: PlainTextRow
	 * @throws:
	 */
	public static TextView createTextMultiColor(TextView tv) {

		String text = tv.getText().toString();
		SpannableString str = new SpannableString(text);
		int color;
		Random rnd = new Random();
		for (int i = 0; i < text.length(); i++) {
			color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
					rnd.nextInt(256));
			str.setSpan(new ForegroundColorSpan(color), i, i,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		tv.setText(str);
		return tv;
	}

	/**
	 * tao dialog voi listener
	 * 
	 * @author: HaiTC
	 * @param activity
	 * @param listener
	 * @param menu
	 * @param title
	 * @param tip
	 * @return: PlainTextRow
	 * @throws:
	 */
	public static AlertDialog showDialog(final String mes, final String btName,
			final OnDialogControlListener listener, final int eventType,
			final int eventCode, final Object data) {
		AlertDialog alertDialog = null;
		try {
			alertDialog = new AlertDialog.Builder((Context) listener).create();
			alertDialog.setMessage(mes);
			alertDialog.setButton(btName,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							listener.onDialogListener(eventType, eventCode,
									data);
							return;

						}
					});
			alertDialog.show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return alertDialog;
	}

	/**
	 * Tao dialog 2 action
	 * 
	 * @author: HaiTC
	 * @param mes
	 * @param btName
	 * @param btName2
	 * @param listener
	 * @param eventType
	 * @param eventCode1
	 * @param eventCode2
	 * @param data
	 * @return
	 * @return: AlertDialog
	 * @throws:
	 */
	public static AlertDialog showDialog(final String mes, final String btName,
			String btName2, final OnDialogControlListener listener,
			final int eventType, final int eventCode1, final int eventCode2,
			final Object data) {
		AlertDialog alertDialog = null;
		try {
			alertDialog = new AlertDialog.Builder((Context) listener).create();
			alertDialog.setMessage(mes);
			alertDialog.setButton(btName,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// xu ly khi dong y doi ngan hang
							dialog.dismiss();
							listener.onDialogListener(eventType, eventCode1,
									data);

						}
					});
			alertDialog.setButton2(btName2,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							listener.onDialogListener(eventType, eventCode2,
									data);
							return;

						}
					});

			alertDialog.show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return alertDialog;
	}

	/**
	 * set so luong hinh anh hien thi tren cho tablet
	 * 
	 * @author: HaiTC
	 * @return: void
	 * @throws:
	 */
	public static SimpleWebImageCache<ThumbnailBus, ThumbnailMessage> getCacheForListThumbs(
			Activity view) {
		// TODO Auto-generated method stub
		int imageSize = (int) view.getResources().getDimension(
				R.dimen.icon_image_small_size);
		ThumbnailBus bus = new ThumbnailBus();
		SimpleWebImageCache<ThumbnailBus, ThumbnailMessage> cache = new SimpleWebImageCache<ThumbnailBus, ThumbnailMessage>(
				null, null, 101, bus);
		if (imageSize == 0)
			return cache;
		int width = view.getWindowManager().getDefaultDisplay().getWidth();
		int height = view.getWindowManager().getDefaultDisplay().getHeight();
		int col = width / imageSize;
		int row = height / imageSize;
		MyLog.e("HaiTC", "numItemVisibleOnScreen  --- " + row * col);
		return cache;
	}

}
